from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication, QFileDialog, QAbstractItemView
from PySide2.QtCore import QAbstractTableModel, QModelIndex, Qt
import pandas as pd

from threading import Thread
import time

class ResultDataModel(QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self._data = data
        self.__hHeader = self._data.columns.tolist()
        self.__vHeader = self._data.index.tolist()

    def rowCount(self, index):
        # The length of the outer list.
        return self._data.shape[0]

    def columnCount(self, index):
        # The following takes the first sub-list, and returns
        # the length (only works if all rows are an equal length)
        return self._data.shape[1]

    def data(self, index, role=Qt.ItemDataRole.DisplayRole):
        if index.isValid():
            if role == Qt.ItemDataRole.DisplayRole or role == Qt.ItemDataRole.EditRole:
                value = self._data.iloc[index.row()][index.column()]
                return str(value)
                # return str(value)

    def setData(self, index, value, role):
        if role == Qt.ItemDataRole.EditRole:
            self._data.iloc[index.row()][index.column()] = value
            print(index.row(), index.column(), value)
            return True
        return False

    def flags(self, index):
        return Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsEditable

    def headerData(self, section, orientation, role):
        if role != Qt.DisplayRole:
            return None
        if orientation == Qt.Horizontal:
            return self.__hHeader[section]
        elif orientation == Qt.Vertical:
            return self.__vHeader[section]

class Demo:
    def __init__(self) -> None:
        self.app = QApplication([])
        self.loginUi = QUiLoader().load("login.ui")
        self.demoUi = QUiLoader().load("demo.ui")

        self.demoUi.tabWidget.tabBar().setVisible(False)
        self.demoUi.tableView.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.SelectedClicked)

        df = pd.DataFrame([[1, 2, 3, 4, 2, 3, 4, 2, 3, 4], [5, 6, 7, 8, 2, 3, 4, 2, 3, 4]], index=['A', 'B'], columns=['One', 'Two', 'Three', 'Four', '', '', '', '', '', ''])
        tableModel = ResultDataModel(df)
        self.demoUi.tableView.setModel(tableModel)

        self.loginUi.loginButton.clicked.connect(self.loginCallback)
        self.demoUi.openFileAction.triggered.connect(self.openPageFile)
        self.demoUi.button0.clicked.connect(self.button0Callback)
        self.demoUi.button1.clicked.connect(self.button1Callback)
        self.demoUi.button2.clicked.connect(self.button2Callback)
    
    def start(self):
        self.loginUi.show()
        self.app.exec_()
    
    def openPageFile(self):
        filePath, _ = QFileDialog.getOpenFileName(
            self.demoUi,
            "选择要打开的文件",
            r".",
            "(*.ui)"
        )
        print("openPageFile, path: ", filePath)


    def loginCallback(self):
        # 获取用户名和密码
        username = self.loginUi.usernameLineEdit.text()
        password = self.loginUi.passwordLineEdit.text()
        print("username:", username)
        print("password:", password)

        # 用户名密码判断
        pass

        # 登录成功切换窗口
        self.loginUi.close()
        self.demoUi.show()

    def button0Callback(self):
        self.demoUi.tabWidget.setCurrentIndex(0)
    
    def button1Callback(self):
        self.demoUi.tabWidget.setCurrentIndex(1)
    
    def button2Callback(self):
        self.demoUi.tabWidget.setCurrentIndex(2)

if __name__ == "__main__":
    print("hello world")
    demo = Demo()

    # def threadFunc():
    #     for i in range(5):
    #         print("current index: ", demo.demoUi.tabWidget.currentIndex())
    #         time.sleep(1)
    
    # thread = Thread(target=threadFunc)
    # thread.start()

    demo.start()